<?php

declare(strict_types=1);

namespace App\Listener;

use App\Constants\System\SysStatusConst;
use App\Constants\User\UserAccountDefaultConst;
use App\Constants\User\UserAccountTypeConst;
use App\Dao\Users\UsersAccountDao;
use App\Events\AfterRegisterHandle;
use App\Model\Users\UsersAccount;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;

#[Listener]
class RegisterListener implements ListenerInterface
{

    #[Inject]
    protected UsersAccountDao $usersAccountDao;
    public function __construct(protected ContainerInterface $container)
    {
    }

    public function listen(): array
    {
        return [
            AfterRegisterHandle::class
        ];
    }

    public function process(object $event): void
    {
        $userInfo = $event->userInfo;
        $shareAccountId = $event->shareAccountId;

        //注册后自动创建一个现金账户
        $defaultAccount = $this->usersAccountDao->add(new UsersAccount(),[
            'uid' => $userInfo->id,
            'amount' => 0,
            'account_name' => '现金账户',
            'in_amount' => 0,
            'out_amount' => 0,
            'is_default' => UserAccountDefaultConst::DEFAULT->value,
            'remark' => '系统创建',
            'is_del' => SysStatusConst::NORMAL->value,
            'type' => UserAccountTypeConst::SYS->value
        ]);

        /**
         * 分享账户再创建一个对应主账号的账册信息
         */
        if($shareAccountId > 0) {
            $userAccountInfo = $this->usersAccountDao->getInfoByPk($shareAccountId);
            //注册后自动创建一个现金账户
            $this->usersAccountDao->add(new UsersAccount(),[
                'uid' => $userInfo->id,
                'amount' => 0,
                'account_name' => $userAccountInfo->account_name,
                'in_amount' => 0,
                'out_amount' => 0,
                'is_default' => UserAccountDefaultConst::DEFAULT->value,
                'remark' => '分享获取',
                'is_del' => SysStatusConst::NORMAL->value,
                'type' => UserAccountTypeConst::SYS->value
            ]);
            $defaultAccount->is_default = UserAccountDefaultConst::NOT_DEFAULT->value;
            $defaultAccount->save();
        }
    }
}
